<?php
/**
 * Created by PhpStorm.
 * User: 子不语
 * Date: 2016/6/16
 * Time: 17:52
 */
class UsersAction extends BaseAction
{
    function __construct()
    {
        $this->no_login=['reg','login'];
        parent::__construct();
    }
    function index(){
        $sql='select tzpoints from game_day_static where uid='.$_SESSION['usersid'];
        $tzpoint=db::get_one($sql);
        $this->assign('tzpoint',number_format($tzpoint->tzpoints));
        $sql='select sum(rmb) from pay_online where state=1 and pay_time=\''.date('Y-m-d').'\' and uid='.$_SESSION['usersid'];
        $rmb=db::get_one($sql);
        $this->assign('rmb',number_format($rmb->rmb));
        $this->display('user_index');
    }
    function out(){
        unset($_SESSION['usersid']);
        session_destroy();
        setcookie("usersid");
        setcookie("username");
        setcookie("password");
        echo "<script language=javascript>location.href='/';</script>";
    }
    function login(){
        if($_POST)return $this->act_login();
        $this->display('login');
    }
    private function act_login(){

        $data=[];
        $data['mobile']=Req::post('mobile');
        $data['password']=Req::post('password');
        $data['captcha']=Req::post('captcha');
        $isKeepLogin = Req::post('iskeep');
        if(!$this->is_mobile($data['mobile'])){
            return $this->result(1,'请输入正确的手机号码');
        }
        if(strlen($data['password'])<6 || strlen($data['password'])>20){
            return $this->result(1,'请保持密码在6-20位之间');
        }
        
        if (strlen($data['captcha']) != 4 || !vcode::check($data['captcha'])) {
            return $this->result(1,'验证码不对');
        }
        $data['password']=$this->setPassword($data['password']);
        if($_SESSION['username']) //用户正在使用
        {
            //return $this->result(1,'用户正在使用');

        }
        $ip=get_ip();
        $sql = "call web_user_login('" . $data['mobile'] . "','" . $data['password'] . "','{$ip}')";
        $arr=db::get_one($sql,'assoc');
        switch($arr["result"])
        {
            case '0': //成功
                $_SESSION["usersid"]=$arr["userid"];
                $_SESSION["username"]= $arr["username"];
                $_SESSION["password"]= $data['password'];
                $_SESSION["nickname"]= $arr["nickname"];
                $_SESSION["points"]=$arr["points"];
                $_SESSION["bankpoints"]=$arr["bankpoint"];
                $_SESSION["exp"]= $arr["experience"];
                $_SESSION["head"]= $arr["head"];
                $_SESSION['freeze']= 0;
                $usersid=$arr["userid"];
                //$res=Db::table('users')->field('u.experience,u.isagent,a.id')->alias('u')->join('agent a','a.uid=u.id and  u.id='.$usersid,'left')->field('u.isagent,a.id,u.experience')->find();

                $res=db::get_one("select u.experience,u.isagent,a.id from users u left join agent a on a.uid=u.id where  u.id={$usersid}",'assoc');
                //var_dump($res);
                if($res['isagent']>0){
                    $_SESSION['isagent']= $res['isagent'];
                    $_SESSION['Agent_Id']= $res['id'];
                }
                $vip_level=0;
                $sql='select id from usergroups where '.$res['experience'].'>=creditslower and '.$res['experience'].'<=creditshigher';
                $level=db::get_one($sql,'assoc');
                if($level['id'])
                {
                    $vip_level = $level['id'];
                }
                $_SESSION['vip_level']= $vip_level;
                if($isKeepLogin == "1")
                {
                    setcookie("usersid",$arr["userid"],time()+3600000);
                    setcookie("username",$arr["username"],time()+3600000);
                    setcookie("password",$data['password'],time()+3600000);
                }
                else
                {
                    setcookie("usersid",$arr["userid"]);
                    setcookie("username",$arr["username"]);
                    setcookie("password",$data['password']);
                }
                $message = 'ok';
                break;
            case '1': //用户名或密码错误
                $message = '用户名或密码错误';
                break;
            case '2': //帐号被冻结
                $message = '帐号被冻结';
                break;
            case '99': //数据库错误
                $message = '数据库错误';
                break;
            default:
                $message = 'other';
                break;
        }

        return $this->result($arr['result'],$message);
    }
    function reg(){
        if($_POST)return $this->act_reg();
        //$v=Config::get('web_pwd_encrypt_prefix');
        //var_dump($v);
        $tj=Req::get('tj','intval');
        if(!$tj)$tj=$_COOKIE['tj']?:0;
        $this->assign('tj',$tj);
        setcookie('tj',$tj,3600);

        return $this->display('user_reg');
		
    }
    function act_reg(){
        $data=[];
        $data['mobile']=Req::post('mobile');
        $data['password']=Req::post('password');
        $data['cpassword']=Req::post('cpassword');
        $data['vercode']=Req::post('vercode');

        $nickname =$username = Req::post('mobile');
        $pass = $data['password'];
        $tjid = Req::post('tjid', 'intval')?:0;
        $nickname = str_replace("http", "", $nickname);
        $nickname = str_replace("href", "", $nickname);
        
        
        if(!$this->is_mobile($data['mobile'])){
            return $this->result(1,'请输入正确的手机号码');
        }
        if(strlen($data['password'])<6 || strlen($data['password'])>20){
            return $this->result(1,'请保持密码在6-20位之间');
        }
        if($data['password']!=$data['cpassword']){
            return $this->result(1,'两次密码不一致');
        }
     
            $sql='select code,account from validcodelog where account='.$username.' order by id desc limit 1';
            $res=db::get_one($sql);
            if($res->code!=$data['vercode']){
                return $this->result(1,'手机验证码不对' );
            }
            $_SESSION['vercode']='';
        
        $data['password']=$this->setPassword($data['password']);
        //unset($data['cpassword']);
        $ip=get_ip();

        $sql = "SELECT id,username,mobile,nickname FROM users WHERE username ='{$username}' or nickname='{$nickname}'";
        $user = db::get_one($sql);

        if ($user->id && $user->username == $username) return $this->result(1, '很抱歉！帐号重名了，请更改！');

        if ($user->nickname == $nickname) return $this->result(1, '很抱歉!昵称重名，请更改！');

        $sql = "SELECT 1 FROM deny_words WHERE deny_type = 'b' AND keyword LIKE '%{$nickname}%'";
        $check_user = db::get_one($sql);
        if ($check_user) return $this->result(1, '很抱歉!用户名含有不允许字符，请更改!');
        //-- 注册赠送豆
        $sql = 'SELECT reg_points,web_loginperience FROM web_config WHERE id = 1';
        $point = db::get_one($sql);
        //uid
        $uid=$this->set_uid();
        //注册
        $pass =$this->setPassword($pass);
        $data = array(
            'id'=>$uid,
            'username' => $username,
            'nickname' => $nickname,
            'password' => $pass,
            'is_check_mobile' => 1,
            'mobile' => $username,
            'bankpwd' => $pass,
            'points' => $point->reg_points,
            'experience' => $point->web_loginperience,
            'maxexperience' => $point->web_loginperience,
            'time' => date('Y-m-d H:i:s'),
            'regip' => $ip,
            'tjid' => $tjid,
            'usertype' => 0,
            'loginip' => $ip,
            'logintime' => date('Y-m-d H:i:s'));
        db::_insert('users', $data);
        if(!$uid)return $this->result(1,'注册失败' );
        //-- 个人统计
        $data = array('uid' => $uid, 'typeid' => 120, 'points' => $point->reg_points);
        db::_insert('game_static', $data);

        //-- 记录中央银行
        if ($point->reg_points > 0) {
            db::_query('UPDATE centerbank SET score = score -' . $point->reg_points . ' WHERE bankIdx = 6');
        }

        //-- 记录统计
        $sql = 'SELECT 1 FROM webtj WHERE `time` = CURDATE()';
        $tj = db::get_one($sql);
        if ($tj) {
            db::_query('UPDATE webtj SET regnum = regnum + 1,regpoints = regpoints + ' . $point->reg_points . '
				WHERE `time` = CURDATE();');
        } else {
            db::_query('INSERT INTO webtj(`time`,regnum,regpoints) VALUES(CURDATE(),1,' . $point->reg_points . ');');
        }

        //-- 记录经验变化日志
        if ($point->web_loginperience > 0) {
            db::_query("INSERT INTO userslog(usersid, `time`, experience, logtype, `log`)
				VALUES({$uid}, NOW(), " . $point->web_loginperience . ", 4, CONCAT('登录奖励', " . $point->web_loginperience . ", '经验值'))");
        }
        //-- 记录登录日志
        db::_insert('login_success', array('uid' => $uid, 'username' => $username,
            'nickname' => $nickname, 'point' => $point->reg_points,
            'bankpoint' => 0,
            'exp' => $point->web_loginperience,
            'loginip' => $ip,
            'login_time' => date('Y-m-d H:i:s')));

        //-- 推荐人数统计
        if ($tjid > 0) {
            db::_query('UPDATE users SET tj_level1_count = tj_level1_count + 1 WHERE id = ' . $tjid);
            db::_query('UPDATE users SET tj_level2_count = tj_level2_count + 1
			WHERE id IN(SELECT * FROM(SELECT tjid FROM users WHERE id = ' . $tjid . ') t');
            db::_query('UPDATE users SET tj_level3_count = tj_level3_count + 1 WHERE id IN(                SELECT * FROM(
                    SELECT tjid FROM users WHERE id IN(SELECT tjid FROM users WHERE id = ' . $tjid . ')) t)');
        }

        $_SESSION["usersid"] = $uid;
        $_SESSION["username"] = $username;
        $_SESSION["password"] = $pass;
        $_SESSION["nickname"] = $nickname;
        $_SESSION["points"] = $point->reg_points;
        $_SESSION["bankpoints"] = 0;
        $_SESSION["exp"] = $point->web_loginperience;
        setcookie("usersid", $uid);
        setcookie("username", $username);
        setcookie("password", $pass);
        setcookie("reg", 1, time() + 8640);
		 return $this->result(1,'注册成功!');
        
        
    }
    function set_uid(){
        $sql='SELECT FLOOR(100000 + RAND()*900000) AS random_num FROM users WHERE "random_num" !=id LIMIT 1';
        $uid=db::get_one($sql);
        if(!$uid)return $this->set_uid();
        return $uid->random_num;
    }
    function changePass(){
        if(IS_AJAX){
            return $this->AjaxChangePass();
        }
        $this->display('change_pass');
    }
    function AjaxChangePass(){
        $t=Req::post('t')?1:0;
        $old=Req::post('old');
        $news=Req::post('news');
        $cnew=Req::post('cnew');
        if(strlen($old)<6){
            return $this->result(1,'密码必须大于6位');
        }
        if(strlen($news)<6 || strlen($news)>20){
            return $this->result(1,'密码在6-20位之间');
        }
        if($news!=$cnew){
            return $this->result(1,'两次密码不一致');
        }
        
        $old=$this->setPassword($old);
        $sql='select password,bankpwd from users where id='.$_SESSION['usersid'];
        $info=db::get_one($sql);
        if($t){
            if($info->password!=$old){
                return $this->result(1,'原密码不对!');
            }
            $sql='update users set password=\''.$this->setPassword($news).'\' where id='.$_SESSION['usersid'];
            db::_query($sql,false);
        }else{
            if($info->bankpwd!=$old){
                return $this->result(1,'原密码不对!');
            }
            db::_update('users',['bankpwd'=>$this->setPassword($news)],'id='.$_SESSION['usersid']);
        }
        return $this->result(0,'修改成功!');
    }
    function mybank(){
        if(IS_AJAX)return $this->Ajax_mybank();

        $this->display('user_mybank');
    }
    function Ajax_mybank(){
        $Score =Req::post('point','intval')?:0;
        $Score*=1000;
        $Pwd = Req::post('pwd')?:"";

        $Pwd =$this->setPassword($Pwd);
        $t=Req::post('t');
        $oprType = ($t=="save")?0:1;
        $ip = get_ip();
        $arrRet = array('cmd'=>'ok','msg'=>'');

        $Score = intval($Score);
        if(!is_numeric($Score) || $Score < 0){
            return $this->result(1,"数量必须为正整数!");
        }

        $sql = "call web_score_process({$_SESSION['usersid']},{$oprType},'{$Pwd}',{$Score},'{$ip}')";
        $arr=db::get_all($sql,'assoc');
        switch($arr[0]["result"])
        {
            case '0': //成功
                $arrRet['cmd'] = "0";
                $arrRet['msg'] = "操作成功!";
                $this->RefreshPoints();
                break;
            case '1':
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = "余额不足!";
                break;
            case '2':
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = "银行密码错误(注:初始密码与登录密码相同)!";
                break;
            default:
                $arrRet['cmd'] = "1";
                $arrRet['msg'] = "系统错误，执行失败!";
                break;
        }
        return $this->result($arrRet['cmd'],$arrRet['msg']);
    }

    function pay(){
        $this->display('user_pay');
    }
    function pay_order(){
        $order_id=Req::get('orderid');
        if(!is_numeric($order_id)){
            echo '订单错误';
            return $this->display();
        }

        $sql = 'select * from pay_online where uid=' . $_SESSION['usersid'] . ' and order_id=\'' . $order_id . '\'';
        $order_info=db::get_one($sql,'assoc');
        if($order_info['cz_type']==1){
            $url='/alipay.png';
            /*
            include_once '/payment/zalipay.php';
            $Pay=new zalipay();
            $result=$Pay->pay($order_id,$order_info['rmb'] );
            var_dump($result);exit;
            if($result['status']==0){
                $url=$result['message'];
            }else{
                header('location:/smbinfo.php?orderid='.$order_id.'&act=recharge_order_pay');
            }*/
        }elseif ($order_info['cz_type']==2){
            /*include_once 'payment/zweichat.php';
            $Pay=new zweichat();
            $result=$Pay->pay($order_id,$order_info['rmb'] );
            var_dump($result);
            if($result['status']==0){
                $url=$result['message'];
            }else{
                //header('location:/smbinfo.php?orderid='.$order_id.'&act=recharge_order_pay');
            }*/
            $url='/weichat.png';
        }elseif ($order_info['cz_type']==2){
            include_once 'payment/wx_qrcode.php';
            $Wx=new wx_qrcode();

            $img=$Wx->get_code(array('order_sn'=>$order_id,'order_amount'=>$order_info['rmb'],'log_id'=>$order_id));
        }
        $this->assign('order_info',$order_info);
        $this->assign('url',$url);
        $this->display('pay_order');
    }
    function bind(){
        $this->display('user_bind');
    }
    function info(){
        if(IS_AJAX)return $this->ajax_info();
        $sql = "select nickname,email,is_check_email,mobile,is_check_mobile,head,qq,caption,username,recv_cash_name
            from users
            where id = '{$_SESSION['usersid']}'";
        $row=db::get_one($sql);

        $str=substr($row->recv_cash_name,3,strlen($row->recv_cash_name));
        $row->recv_cash_name=str_replace($str,"***",$row->recv_cash_name);

        $str=substr($row->qq,4,strlen($row->qq));
        $row->qq_show=str_replace($str,"*****",$row->qq);
        $row->qq=str_replace($str,"aaaa",$row->qq);
        $this->assign('row',$row);
        $this->display('user_info');
    }
    function ajax_info(){
        $NickName = isset($_POST['nickname'])?(Req::post('nickname')):"";
        $Head = isset($_POST['head'])?Req::post('head'):"";
        $Mobile = isset($_POST['mobile'])?Req::post('mobile'):"";
        $Email = isset($_POST['email'])?(Req::post('email')):"";
        $QQ = isset($_POST['qq'])?Req::post('qq'):"";
        $Caption = isset($_POST['caption'])?(Req::post('caption')):"";
        $arrRet = array('cmd'=>'ok','msg'=>'');
        $recv_cash_name = isset($_POST['recv_cash_name'])?(Req::post('recv_cash_name')):"";
        if($NickName == "" || strlen($NickName) > 20){
            $this->result(1,'昵称错误,长度不超过20位!');
        }
        if($Mobile == "" || !is_numeric($Mobile) || strlen($Mobile) > 11) {
            $this->result(1,'请输入常用的手机号码');
        }
        $QQ = (strlen($QQ) > 20) ? substr($QQ,0,20) : $QQ;
        $Head=str_replace("1/","1",$Head);
        $Head=str_replace("0/","0",$Head);
        $Head = "img/head/" . $Head;
        $sql = "update users set nickname='{$NickName}',head='{$Head}',mobile='{$Mobile}',email='{$Email}',caption='{$Caption}'
				where id = '{$_SESSION['usersid']}'";
        //WriteLog($sql);
        $_SESSION["head"] = $Head;
        $result =  db::_query($sql);
        if($recv_cash_name!=""){
            $sql = "update users set recv_cash_name='{$recv_cash_name}' where id = '{$_SESSION['usersid']}' and recv_cash_name='' ";
            db::_query($sql);
        }
        if($QQ!=""){
            $sql = "update users set qq='{$QQ}' where id = '{$_SESSION['usersid']}' and qq='' ";
            db::_query($sql);
        }
        $this->result(0,'修改成功!');
    }
}